import { createVNode, DirectiveBinding, ObjectDirective, render } from 'vue';

const SUCCESS = '#72c140';
const ERROR = '#ed5b56';
const WARNING = '#f0af41';
const INFO = '#4091f7';
const HEIGHT = 20;
let flag = false;

const Badge: ObjectDirective = {
	updated(el: HTMLElement, binding: DirectiveBinding) {
		const { modifiers, value } = binding;
		const modifiersKey = Object.keys(modifiers);
		const isDot = modifiersKey.includes('dot');
		let backgroundColor = '';
		if (modifiersKey.includes('success')) {
			backgroundColor = SUCCESS;
		} else if (modifiersKey.includes('warning')) {
			backgroundColor = WARNING;
		} else if (modifiersKey.includes('info')) {
			backgroundColor = INFO;
		} else {
			backgroundColor = ERROR;
		}

		const targetTemplate = isDot
			? `<div style="position:absolute;top:-5px;right:-5px;height:10px;width:10px;border-radius:50%;background:${backgroundColor}"></div>`
			: `<div style="background:${backgroundColor};position:absolute;top:-${
					HEIGHT / 2
			  }px;right:-${
					HEIGHT / 2
			  }px;height:${HEIGHT}px;min-width:${HEIGHT}px;border-radius:${
					HEIGHT / 2
			  }px;text-align:center;line-height:${HEIGHT}px;color:#fff;padding:0 5px;">${value}</div>`;

		el.style.position = el.style.position || 'relative';
		//将options参数传入，并将badge组件转换成虚拟DOM，并赋值给app
		const badge = createVNode({
			template: targetTemplate,
		});
		//创建一个空的span
		const mountNode = document.createElement('span');
		mountNode.className = 'ibiz-badge';
		//render函数的作用就是将badge组件的虚拟DOM转换成真实DOM并插入到mountNode元素里
		render(badge, mountNode);
		if (value) {
			if (flag && el.lastChild) {
				el.removeChild(el.lastChild);
			}
			el.appendChild(mountNode);
			flag = true;
		}
	},
};

export default Badge;
